package controllers

import javax.inject.Inject

import play.api.libs.json.Json
import play.api.mvc._
import dao._
import models.Tables._
import scala.concurrent.ExecutionContext.Implicits.global

class MarkerController @Inject()(cc:ControllerComponents,indelDao: IndelDao, ssrDao: SsrDao, paperDao: PaperDao) extends AbstractController(cc) {

  def toIndel = Action {
    Ok(views.html.marker.indel())
  }

  def toSsr = Action {
    Ok(views.html.marker.ssr())
  }

  def toPaper = Action {
    Ok(views.html.marker.paper())
  }

  def getAllIndels = Action.async { implicit request =>
    indelDao.selectAll.map { x =>
      val array = getArrayByIndels(x)
      Ok(Json.toJson(array))
    }
  }

  def getAllSsrs = Action.async { implicit request =>
    ssrDao.selectAll.map { x =>
      val array = getArrayBySsrs(x)
      Ok(Json.toJson(array))
    }
  }

  def getAllPapers = Action.async { implicit request =>
    paperDao.selectAll.map { x =>
      val array = getArrayByPapers(x)
      Ok(Json.toJson(array))
    }
  }

  def getArrayByPapers(x: Seq[PaperRow]) = {
    x.map { y =>
      Json.obj(
        "name" -> y.name, "frontPrimer" -> y.frontprimer, "lastPrimer" -> y.lastprimer, "kind" -> y.kind,
        "use" -> y.use
      )
    }
  }

  def getArrayBySsrs(x: Seq[SsrRow]) = {
    x.map { y =>
      Json.obj(
        "name" -> y.name, "fPrimer" -> y.fprimer, "rPrimer" -> y.rprimer, "productSize" -> y.productsize,
        "ssrSequences" -> y.ssrsequences, "sourceContigs" -> y.sourcecontigs,
        "forwardchr" -> y.forwardchr, "forwardposition" -> y.forwardposition
      )
    }
  }

  def getArrayByIndels(x: Seq[IndelRow]) = {
    x.map { y =>
      val idStr = "<a target='_blank' title='more' href='" + routes.MarkerController.getIndelDetailInfo(y.id) + "'>" + y.id + "</a>"
      Json.obj(
        "id" -> idStr, "gapsize" -> y.gapsize, "forwardprimer" -> y.forwardprimer, "tm" -> y.tm,
        "reverseprimer" -> y.reverseprimer, "forwardchr" -> y.forwardchr, "forwardposition" -> y.forwardposition
      )
    }
  }

  def getIndelDetailInfo(id: String) = Action.async { implicit request =>
    indelDao.selectById(id).map(_.get).map { x =>
      Ok(views.html.marker.indelDetailInfo(x))
    }
  }

}
